<?php
namespace App\Services;

use Illuminate\Http\Request;
use App\Models\SysUser;

/**
 * 系统用户服务类
 * @package App\Services
 */
class SysUserService
{
    /**
     * 构造函数
     */
    public function __construct()
    {

    }

    /**
     * 获取用户数据
     * @param $id
     * @return mixed
     */
    public function get($id)
    {
        return SysUser::findOrFail($id);
    }
    /**
     * 新建或编辑用户
     * @param $request
     * @return bool
     */
    public function save($request)
    {
        $id = $request->input('id', 0);
        if ($id){
            $user = SysUser::find($id);
        }else{
            $user = new SysUser;
        }
        $user->name = $request->input('name', '');
        $user->email = $request->input('email','');
        $password = $request->input('password', '');
        if ($password){
            $user->password = bcrypt($password);
        }
        return $user->save();
    }

    /**
     * 更改用户状态
     * @param $id
     * @param $status
     * @return mixed
     */
    public function changestatus($id, $status)
    {
        $user = SysUser::withTrashed()->findOrFail($id);
        if($status == 1){
            return $user->restore();
        }else{
            return $user->delete();
        }
    }

    /**
     * 保存用户角色
     * @param $userId
     * @param $roleIds
     * @return mixed
     * @throws \Exception
     */
    public function saveRole($userId, $roleIds)
    {
        $user = SysUser::withTrashed()->findOrFail($userId);
        if (empty($roleIds)){
            throw new \Exception('请选择用户组');
        }
        return $user->roles()->sync($roleIds);
    }
}